package com.db.utils;

import com.properties.ProPertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/4/26 9:59
 * @since JDK 1.8
 */
@Component
@Slf4j
public class DBService {

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String dbUsername;

    @Value("${spring.datasource.password}")
    private String dbPassword;

    @Value("${spring.datasource.driver-class-name}")
    private String dbDriver;

    @Value("${spring.datasource.type}")
    private String dbType;

    @Value("${DB.datatable}")
    private String dbTable;

    private static Map<String, String> propertiesMap = new HashMap<>();

    private static final String devPATH=System.getProperty("user.dir");


    //数据库信息初始化
    @Bean
    private void DBInit(){
        DBUtils.initDBUtils(dbUrl,dbDriver,dbPassword,dbUsername);
    }

    //初始化数据库连接配置信息
    @Bean
    private void initProperties(){
        ProPertiesUtils.loadProperties("sql",propertiesMap);
        log.info("数据库信息初始化成功");
    }

    @Bean
    private void tempDataTable(){
        String filePath=devPATH+File.separator+"dbtemp";
        String dbName="spring-demo";//备份的数据库名
        String result= DBTempUtils.tempDB(dbName,filePath);
        log.info("数据库备份成功："+result);
    }

//    @Bean
//    private void test33(){
//        log.info("test33333");
//        Map<String, String> stringStringMap=new HashMap<>();
//        File file=new File("C:\\Users\\xiong\\Desktop\\test.properties");
//        ProPertiesUtils.loadProperties(file,stringStringMap);
//        stringStringMap.forEach((k,v)->{
//            System.out.println(k+" "+v);
//        });
//    }


    /**
     * 获取数据库名称
     * @return
     */
    public String getDbTable(){
        return dbTable;
    }


    /**
     * 获取当前项目的所有数据库
     * @return
     */
    public List<Map<String, Object>> getTableNames(){
        String sql=propertiesMap.get("showtables");
        String dbTable=getDbTable();
        return DBUtils.selectMapList(sql,new String[]{dbTable});
    }










}
